<template>
  <a-spin :delay="200" tip="加载中..." :spinning="loading" wrapper-class-name="loading">
    <a-card v-if="!loading" class="body-container">
      <s-list-form
        :enable-more="config.general.more"
        @change="
          $nextTick(() => {
            $calcTableHeight()
          })
        "
      >
        <template #less>
          <s-dynamic-form :items="config.search.less.items" :form="query"> </s-dynamic-form>
        </template>
        <template #more>
          <s-dynamic-form :items="config.search.more.items" :form="query"> </s-dynamic-form>
        </template>
      </s-list-form>
      <s-tool-bar>
        <template #left>
          <s-button
            v-if="permissions.add"
            icon="plus-outlined"
            type="primary"
            @click="
              () => {
                $refs.addDialog.init('/workflow/flow/selectFormByFlowType', { flowType: flowType })
              }
            "
          >
            新增
          </s-button>
        </template>
        <template #right>
          <s-button type="primary" icon="search-outlined" @click="search">查询</s-button>
          <s-button
            style="margin-left: 8px"
            icon="stop-outlined"
            @click="
              () => {
                query = {}
              }
            "
            >重置</s-button
          >
        </template>
      </s-tool-bar>
      <s-table
        ref="table"
        bordered
        :echos="echos"
        :scroll="{ y: tableHeight }"
        :columns="columns"
        :url="config.interface.list"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a
              v-if="record.task != null && isMyTask(record.task)"
              style="margin-right: 8px"
              @click="openHandleTask(record)"
            >
              <s-icon type="clock-circle-outlined" />{{ record.task.operationName }}
            </a>
            <a
              style="margin-right: 8px"
              @click="
                $refs.flowHistory.open(
                  record.id,
                  record.state.workFlowDefineId,
                  record.state.processDefineId
                )
              "
            >
              <s-icon type="clock-circle-outlined" />流程历史
            </a>
            <a
              style="margin-right: 8px"
              @click="
                $refs.flowState.open(
                  record.state.processDefineId,
                  record.id,
                  record.state.workFlowDefineId
                )
              "
            >
              <s-icon type="clock-circle-outlined" />流程状态
            </a>
          </template>
        </template>
      </s-table>
      <flow-start-dialog ref="addDialog" title="新增" @save="add" />
      <flow-handle-dialog ref="handleDialog" @save="handle" />
      <flow-history ref="flowHistory" />
      <flow-state ref="flowState" />
    </a-card>
  </a-spin>
</template>
<script>
import FlowStartDialog from '@/pages/components/FlowStartDialog.vue'
import FlowHandleDialog from '@/pages/components/FlowHandleDialog.vue'
import FlowHistory from '@/pages/components/FlowHistory.vue'
import FlowState from '@/pages/components/FlowState.vue'
export default {
  name: 'WorkFlowModelTable',
  components: { FlowStartDialog, FlowHistory, FlowState, FlowHandleDialog },
  data() {
    return {
      itemFormValue: {},

      operation: false,
      echos: [],
      loading: true,
      query: {},
      permissions: {
        add: true,
        update: true,
        delete: true,
        detail: true
      },
      config: {
        general: {
          more: false
        },
        search: {
          index: 0,
          less: {
            items: []
          },
          more: {
            items: []
          }
        },
        hooks: {
          query: null
        },
        interface: {
          custom: false,
          add: '',
          update: '',
          list: '',
          delete: '',
          deleteMulti: ''
        }
      },
      columns: []
    }
  },
  created() {
    const moduleId = this.$route.query.id
    const flowType = this.$route.query.flowType
    this.flowType = flowType
    // 加载模块...
    this.$api.GET('/code/module/selectOneById', { id: moduleId }).then((res) => {
      if (res.data) {
        this.$api
          .GET('/code/model/selectOneById', { id: res.data.moduleValue.model })
          .then((res2) => {
            if (res2.data) {
              this.init(res.data, res2.data)
            }
          })
      }
    })
  },
  methods: {
    isMyTask(task) {
      const user = this.$realm.user
      if (!task.assignTo) {
        return true
      }
      let assigns = task.assignTo.split(',')
      if (assigns.indexOf(user.userName) > -1 || assigns.indexOf('dept:' + user.orgId) > -1) {
        return true
      }
      return false
    },
    openHandleTask(record) {
      this.selectItem = record
      this.$refs.handleDialog.init(
        '/workflow/flow/selectFormByTaskKeyAndProcessDefinitionId',
        { taskKey: record.task.taskKey, processDefineId: record.state.processDefineId },
        record.task.taskName,
        record.task.operationName
      )
    },
    add(values, fullValue) {
      this.$api
        .PUT(this.config.interface.add, values)
        .then((res) => {
          this.$refs.addDialog.close()
          this.$refs.table.refresh()
        })
        .catch(() => {
          this.$refs.addDialog.resetLoading()
        })
    },
    handle(values, fullValue) {
      let url = this.selectItem.task.apiPath
      url = url.replace('{taskId}', this.selectItem.task.taskId)
      const data = Object.assign({ id: this.selectItem.id }, values)
      this.$api
        .POST(url, data, { dataType: 'json' })
        .then((res) => {
          this.$refs.handleDialog.close()
          this.$refs.table.refresh()
        })
        .catch(() => {
          this.$refs.handleDialog.resetLoading()
        })
    },
    formatTableColumn(fakeColumns) {
      let newColumn = []
      let echos = []
      fakeColumns.forEach((item) => {
        let newItem = {
          dataIndex: item.echo ? item.dataIndex + 'Name' : item.dataIndex,
          title: item.title,
          width: item.width,
          sorter: item.sorter,
          ellipsis: item.ellipsis
        }
        if (item.echo) {
          echos.push({
            name: item.dataIndex,
            label: item.echoLabel,
            value: item.echoValue,
            url: item.echoUrl
          })
        }
        newColumn.push(newItem)
      })
      newColumn.push({
        title: '操作',
        fixed: 'right',
        key: 'action',
        width: 300
      })
      this.echos = echos
      this.columns = newColumn
    },
    init(module, model) {
      try {
        this.operation = model.modelForm.operation == '1'
        this.config = module.moduleList.config
        //初始化url
        if (!this.config.interface.custom) {
          console.error('error!模型表单必须自定义接口')
        }
        //初始化权限
        if (module.moduleValue.authCheck == '1') {
          this.permissions.add = this.$hasPermission(
            'skrivet:' + module.moduleValue.code + ':add',
            'and'
          )
          this.permissions.delete = this.$hasPermission(
            'skrivet:' + module.moduleValue.code + ':delete',
            'and'
          )
          this.permissions.detail = this.$hasPermission(
            'skrivet:' + module.moduleValue.code + ':detail',
            'and'
          )
          this.permissions.update = this.$hasPermission(
            'skrivet:' + module.moduleValue.code + ':update',
            'and'
          )
        }
        //初始化column
        let fakeColumns = module.moduleList.tableColumns
        this.formatTableColumn(fakeColumns)
        this.loading = false
        this.$nextTick(() => {
          this.$calcTableHeight()
        })
      } catch (e) {
        console.log(e)
      }
    },
    search() {
      const _this = this
      const query = Object.assign({}, this.query)
      if (this.config.hooks.query) {
        // eslint-disable-next-line no-eval
        eval('(query,_this)=>{  ' + this.config.hooks.query + '}')(query, _this)
      }
      this.$refs.table.search(query)
    }
  }
}
</script>
<style>
.loading {
  height: 100%;
}
</style>
